<?php

	/**
	 * Crawls restaurant item from restaurantlog.com
	 *
	 * @author anton.perkin
	 * @version 1.0
	 *
	 */
	class OpenTable implements RestaurantSource
	{
		/* VARIABLES */
		
		/**
		 * Restaurant list base URL
		 *
		 * @var string
		 */
		public $listUrl = 'http://www.opentable.com/*-restaurant-listings';

		/**
		 * States list URL
		 *
		 * @var string
		 */
		public $statesUrl = 'http://www.opentable.com/state.aspx';
		
		/**
		 * Restaurant item base URL
		 *
		 * @var string
		 */
		public $itemUrl = 'http://www.opentable.com/state.aspx';

		/**
		 * State URLs
		 *
		 * @var array
		 */
		public $stateURLs;
		
		/**
		 * Listing URLs
		 *
		 * @var array
		 */
		public $listingURLs = array();
		
		/**
		 * Restaurant URLs
		 *
		 * @var array
		 */
		public $restaurantURLs;
		
		
		/* CONSTRUCTORS */
			
		/**
		 * Defualt constructor
		 *
		 */
		public function OpenTable()
		{
			
		}		
		
		
		/* METHODS */
		
		/**
		 * Gets list of restaurant URLs
		 * 
		 */
		public function GetRestaurantUrls()
		{
			$urls = $this->GetSavedListingURLs();
			
			foreach ($urls as $url)
			{
				//parsed page
//				$page = phpQuery::newDocumentFileHTML(str_replace('*', $cityName, $this->listUrl));
				$page = phpQuery::newDocumentFileHTML($url['url']);
				
				$results = $page->find(".rinfo > a");
				foreach ($results as $result)
				{
					$this->restaurantURLs[] = pq($result)->attr('href');
				}				
			}

		}
		
		/**
		 * Gets list of states URLs
		 * 
		 */
		public function GetStateUrls()
		{
			//parsed page
			$page = phpQuery::newDocumentFileHTML($this->statesUrl);
			
			$results = $page->find(".arealist a");
			foreach ($results as $result)
			{
				if (strstr(pq($result)->attr('href'), 'city.aspx'))
				{
					$this->stateURLs[] = 'http://www.opentable.com/'.pq($result)->attr('href');
				}
			}
		}		
		
		/**
		 * Gets list of listing URLs
		 * 
		 */
		public function GetListingUrls()
		{
			$stateURLs = $this->GetSavedStateURLs();
			
			//sections
			$groupURLs = array();
			foreach ($stateURLs as $count => $stateURL)
			{
				$page = phpQuery::newDocumentFileHTML($stateURL['url']);
				
				$groups = $page->find(".arealist a");
				foreach ($groups as $group)
				{
					$groupURL = 'http://www.opentable.com/'.pq($group)->attr('href');
					if (!in_array($groupURL, $groupURLs)) 
					{
						$groupURLs[] = $groupURL;
						$page = phpQuery::newDocumentFileHTML($groupURL);
						$sectionURL = $page->find("#SearchNav_hlBrowseAllRestaurants")->attr('href');
						if (!in_array($sectionURL, $this->listingURLs))
						{
							$this->listingURLs[] = $sectionURL;
						}
					}
				}
//				if ($count > 2) break;
			}	
	
		//	$listURLs = array();
		//	for ($i = 1; $i <= 100; $i++)
		//	{
		//		$listURL = 'http://www.opentable.com/rest_list.aspx?m='.$i;
		//		$page = phpQuery::newDocumentFileHTML($listURL);
		//		
		//		$title = $page->find("#AlRestList_lblHeaderMessage")->html();
		//		
		//		echo "<a href = '$listURL'>$title</a><br />";
		//	}	
		}		
		
		/**
		 * Saves restaurant URLs
		 * 
		 * @return boolean
		 *
		 */
		public function SaveRestaurantURLs()
		{
			$result = array('success' => 0, 'fail' => 0);

			foreach ($this->restaurantURLs as $url)
			{
				$restaurantItem = new RestaurantItem();
				$saveResult = $restaurantItem->SaveURL('http://www.opentable.com/'.$url, 'opentable');
				if ($saveResult)
				{
					$result['success']++;
				}
				else 
				{
					$result['fail']++;
				}
			}
			
			return $result;
		}
		
		/**
		 * Saves state URLs
		 * 
		 * @return boolean
		 *
		 */
		public function SaveStateURLs()
		{
			$result = array('success' => 0, 'fail' => 0);

			foreach ($this->stateURLs as $url)
			{
				if (DB::ExecuteSQL("
					INSERT INTO t_restaurant_state_urls
					(
						url
					)
					VALUES
					(
						'$url'
					);
				") === true)
				{
					$saveResult = true;
				}	
				else 
				{
					$saveResult = false;
				}				
				
				if ($saveResult)
				{
					$result['success']++;
				}
				else 
				{
					$result['fail']++;
				}
			}
			
			return $result;
		}		
		
		/**
		 * Saves listing URLs
		 * 
		 * @return boolean
		 *
		 */
		public function SaveListingURLs()
		{
			$result = array('success' => 0, 'fail' => 0);

			foreach ($this->listingURLs as $url)
			{
				if (DB::ExecuteSQL("
					INSERT INTO t_restaurant_listing_urls
					(
						url
					)
					VALUES
					(
						'$url'
					);
				") === true)
				{
					$saveResult = true;
				}	
				else 
				{
					$saveResult = false;
				}				
				
				if ($saveResult)
				{
					$result['success']++;
				}
				else 
				{
					$result['fail']++;
				}
			}
			
			return $result;
		}		
		
		/**
		 * Gets restaurant URLs list
		 *
		 * @param int $fromRecord offset
		 * @param int $toRecord count
		 */
		public function GetSavedRestaurantURLs($fromRecord = '', $toRecord = '')
		{
			//limit
			if (($fromRecord == '') && ($toRecord == ''))
			{
				$limit = '';
			}
			else 
			{
				$fromRecord = ($fromRecord == '') ? 0 : $fromRecord;
				$toRecord = ($toRecord == '') ? 1000000 : $toRecord;
				$limit = "LIMIT $fromRecord, $toRecord";
			}
			
			$urls = DB::ListItems("
				SELECT * FROM t_restaurant_urls WHERE source = 'opentable' $limit;
			");
			
			return $urls;
		}
		
		/**
		 * Gets restaurant URLs list
		 *
		 * @param int $fromRecord offset
		 * @param int $toRecord count
		 */
		public function GetSavedRestaurantURLsByIds($ids)
		{
			$urls = DB::ListItems("
				SELECT * FROM t_restaurant_urls WHERE source = 'opentable' AND id IN ($ids);
			");

			return $urls;
		}		
		
		/**
		 * Gets state URLs list
		 *
		 */
		public function GetSavedStateURLs()
		{
			$urls = DB::ListItems("
				SELECT * FROM t_restaurant_state_urls;
			");
			
			return $urls;
		}		
		
		/**
		 * Gets listing URLs list
		 *
		 */
		public function GetSavedListingURLs()
		{
			$urls = DB::ListItems("
				SELECT * FROM t_restaurant_listing_urls;
			");
			
			return $urls;
		}		
		
		/**
		 * Gets restaurant item
		 * 
		 * @param int $id restaurant id
		 * 
		 * @return RestaurantItem
		 *
		 */
		public function GetRestaurantItem($url)
		{
			//parsed page
			$page = phpQuery::newDocumentFileHTML($url);

			//restaurant info
			$restaurantInfo = $page->find("#content");
			
			//restaurant item
			$restaurantItem = new RestaurantItem();
			
			$restaurantItem->id = $page->find("#RestaurantProfile_RestSearchBox_txtHid_RestaurantID")->attr('value');
			
			//name
			$restaurantItem->name = trim($page->find(".RestProfileTitle")->html());
			
			//cuisine
			$restaurantItem->cuisine = $this->ParseInfoItem(pq($restaurantInfo)->find("#RestaurantProfile_RestaurantProfileInfo_lblCuisine")->html());
			
			$fullAddress = $page->find(".RestProfileAddress")->html();
			$fullAddressComponents = explode('<br>', trim($fullAddress));
			$componentsCount = count($fullAddressComponents);
			$fullAddressComponents1 = explode(',', trim($fullAddressComponents[$componentsCount-1]));
			$fullAddressComponents2 = explode(' ', trim($fullAddressComponents1[1]));
			
			$restaurantItem->addressLine1 = trim($fullAddressComponents[0]);
//			$restaurantItem->addressLine1 = trim(strip_tags($page->find(".RestProfileAddress")->html()));
			$restaurantItem->addressLine2 = '';
			$restaurantItem->city = trim($fullAddressComponents1[0]);
			$restaurantItem->state = trim($fullAddressComponents2[0]);
			$restaurantItem->zip = trim($fullAddressComponents2[2]);
			$restaurantItem->country = 'USA';
			$restaurantItem->phone = $this->ParseInfoItem(pq($restaurantInfo)->find("#RestaurantProfile_RestaurantProfileInfo_lblPhone")->html());
			$restaurantItem->email = pq($restaurantInfo)->find("#RestaurantProfile_RestaurantProfileInfo_lblEmail > a")->html();
			$restaurantItem->pricePoint = $this->ParseInfoItem(pq($restaurantInfo)->find("#RestaurantProfile_RestaurantProfileInfo_lblPrice")->html());
			
			//item url
			$restaurantItem->webAddress = $url;
			
			//image url
			$restaurantItem->photoURL = $page->find("#RestaurantProfile_linkRestarantImage img")->attr('src');
			
			//source
			$restaurantItem->source = 'opentable';
			
			return $restaurantItem;
		}
		
		/**
		 * Parses info item
		 *
		 * @param string $item item content
		 */
		private function ParseInfoItem($item)
		{
			return trim(str_ireplace(':', '', eregi_replace('<b>.*</b>', '', $item)));
//			return trim(str_ireplace(':', '', str_ireplace("<b>$name</b>", '', $item)));
		}
	}

?>